<template>
  <div class="contianer">
    <el-container class="contianer">
      <el-menu
        default-active="1-4-1"
        class="el-menu-vertical-demo"
        :unique-opened="true"
        :collapse="isCollapse"
      >
        <el-menu-item index="0">
          <img
            v-if="!isCollapse"
            src="../../assets/logo.svg"
            @click="opemMenu"
            style="height: 38px"
          />
          <img
            v-else
            src="../../assets/logo.svg"
            @click="opemMenu"
            style="height: 25px"
          />
          <span slot="title" style="text-align: center; font-family: 'PingFang SC'"
            >&nbsp;&nbsp;&nbsp;围群管理</span
          >
        </el-menu-item>
        <el-menu-item index="1" @click="toIndex()">
          <i class="el-icon-menu" @click="toIndex()"></i>
          <span slot="title" @click="toIndex()">首页</span>
        </el-menu-item>
        <el-submenu index="2">
          <template slot="title">
            <i class="el-icon-reading"></i>
            <span slot="title">博客</span>
          </template>
          <el-menu-item-group>
            <el-menu-item index="1-1" @click="toArticle()"
              ><i class="el-icon-tickets"></i>博客文章</el-menu-item
            >
            <!-- <el-menu-item index="1-2" @click="toNodeList()"><i class="el-icon-edit"></i>随手笔记</el-menu-item> -->
            <el-menu-item index="1-3" @click="toProjectAdmin()"
              ><i class="el-icon-coin"></i>项目管理</el-menu-item
            >
            <!-- <el-menu-item index="1-4" @click="toCodeAdmin()"><i class="el-icon-cpu"></i>源码管理</el-menu-item> -->
            <el-menu-item index="1-5" @click="toTagTypeAdmin()"
              ><i class="el-icon-collection-tag"></i>标签类型管理</el-menu-item
            >
            <el-menu-item index="1-6" @click="toTagAdmin()"
              ><i class="el-icon-magic-stick"></i>标签管理</el-menu-item
            >
          </el-menu-item-group>
        </el-submenu>
        <el-submenu index="3">
          <template slot="title">
            <i class="el-icon-set-up"></i>
            <span slot="title">系统管理</span>
          </template>
          <el-menu-item-group>
            <el-menu-item index="3-1" @click="toUserAdmin()"
              ><i class="el-icon-user"></i>用户管理</el-menu-item
            >
            <el-menu-item index="3-2" @click="toRoleAdmin()"
              ><i class="el-icon-s-custom"></i>角色管理</el-menu-item
            >
            <el-menu-item index="3-3" @click="toMenuAdmin()"
              ><i class="el-icon-s-check"></i>权限管理</el-menu-item
            >
          </el-menu-item-group>
        </el-submenu>

        <!-- <el-menu-item index="3" @click="toUserAdmin()">
          <i class="el-icon-user" @click="toUserAdmin()"></i>
          <span slot="title" @click="toUserAdmin()">用户管理</span>
        </el-menu-item> -->

        <el-menu-item index="4" @click="toCommunity()">
          <i class="el-icon-chat-dot-round" @click="toCommunity()"></i>
          <span slot="title" @click="toCommunity()">围群社区</span>
        </el-menu-item>

        <el-menu-item index="5" @click="toAboutAdmin()">
          <i class="el-icon-guide" @click="toAboutAdmin()"></i>
          <span slot="title" @click="toAboutAdmin()">关于围群</span>
        </el-menu-item>
        <el-menu-item index="6" disabled>
          <i class="el-icon-loading"></i>
          <span slot="title">正在开发...</span>
        </el-menu-item>
      </el-menu>

      <el-container>
        <el-header
          style="
            text-align: right;
            font-size: 12px;
            background-color: #85d9d8;
            min-width: 1300px;
          "
        >
          <!-- <el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab" class="tabs">
            <el-tab-pane
              v-for="(item, index) in editableTabs"
              :key="item.name"
              :label="item.title"
              :name="item.name"
            >
            </el-tab-pane>
          </el-tabs> -->

          <div class="breadcrumb-class">
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-for="item in breadList">{{
                item.meta.title
              }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="search-box">
            <input
              type="text"
              v-model="search"
              class="search-txt"
              placeholder="search..."
              @keyup.enter="searchFun"
            />
            <a class="search-btn" @click="searchFun">
              <span class="fa fa-search" @click="searchFun"></span>
            </a>
          </div>
          <el-dropdown trigger="click" class="userDropdown">
            <span class="el-dropdown-link">
              <div class="userHeadimg">
                <el-avatar
                  shape="square"
                  :size="40"
                  :src="userMess.avatar ? userMess.avatar : circleUrl"
                ></el-avatar>
              </div>
              <div class="userName">
                {{ userMess.nickName }}<i class="el-icon-arrow-down el-icon--right"></i>
              </div>
            </span>
            <el-dropdown-menu
              slot="dropdown"
              style="background-color: #ebe8e8; width: 130px"
            >
              <el-dropdown-item @click.native="baseMess"
                ><i class="el-icon-edit-outline"></i>&nbsp;基本信息</el-dropdown-item
              >
              <el-dropdown-item @click.native="changePassBtn"
                ><i class="el-icon-key"></i>&nbsp;密码修改</el-dropdown-item
              >
              <el-dropdown-item @click.native="loginOut"
                ><i class="el-icon-switch-button"></i>&nbsp;退出登录</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>

        <el-main style="height: 1000px" class="main">
          <el-backtop target=".main" :visibility-height="100"></el-backtop>
          <!-- 页面主题部分，路由出口 -->
          <!-- <router-view /> -->
          <transition name="fade" mode="out-in">
            <keep-alive>
              <router-view v-if="$route.meta.keepAlive"></router-view>
            </keep-alive>
          </transition>
          <router-view v-if="!$route.meta.keepAlive"></router-view>
        </el-main>
      </el-container>
    </el-container>

    <el-dialog
      :visible.sync="isChangePass ? true : changePass"
      :width="'800px'"
      :height="'400px'"
    >
      <div slot="title" class="header-title">
        <span class="title-name">
          <i class="el-icon-edit" style="margin-right: 10px"></i>
        </span>
        <span class="title-age">密码修改</span>
      </div>
      <div class="changePass">
        <el-steps :active="active" finish-status="success">
          <el-step title="身份验证"></el-step>
          <el-step title="新密码"></el-step>
          <el-step title="修改成功"></el-step>
        </el-steps>
        <div class="changePassMiddle">
          <div class="changePassCode" v-if="active == 0">
            <!-- <el-input placeholder="请输入手机号" v-model="smsCode.phone" maxlength="10" show-word-limit clearable></el-input> -->
            <el-input
              v-model="smsCode.sms"
              placeholder="验证码"
              style="width: 60%; top: 30px"
            ></el-input
            >&nbsp;

            <el-button
              type="primary"
              :disabled="disable"
              :class="{ codeGeting: isGeting }"
              style="position: absolute; width: 32%; top: 60px"
              @click="getVerifyCode"
              >{{ getCode }}</el-button
            >
            <div
              style="
                position: absolute;
                width: 100%;
                top: 130px;
                color: rgb(230, 162, 60);
              "
              v-show="sendCode"
            >
              <i class="el-icon-warning"></i
              >&nbsp;验证码已发送至您的邮箱，一分钟内有效，请注意查收!
            </div>
          </div>
          <div class="outNewPass" v-if="active == 1">
            <el-form
              :model="ruleForm"
              status-icon
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item label="密码" prop="pass">
                <el-input
                  type="password"
                  v-model="ruleForm.pass"
                  autocomplete="off"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input
                  type="password"
                  v-model="ruleForm.checkPass"
                  autocomplete="off"
                  clearable
                ></el-input>
              </el-form-item>
            </el-form>
          </div>

          <div
            class="succesChangePass"
            v-if="active == 2"
            style="position: absolute; top: 0px; left: 20px"
          >
            <el-result
              icon="warning"
              title="密码修改失败"
              subTitle="将检查网络后重新进行密码修改"
            >
            </el-result>
          </div>
          <div
            class="succesChangePass"
            v-if="active == 3"
            style="position: absolute; top: 0px; left: 20px"
          >
            <el-result
              icon="success"
              title="密码修改成功"
              :subTitle="subTitle ? subTitle : '请重新登录, 5 秒钟之后自动退出登录...'"
            >
            </el-result>
          </div>
        </div>
        <div class="changePassBotton">
          <el-button
            type="info"
            style="margin-top: 12px"
            @click="active--"
            v-if="active == 1 || active == 2"
            ><i class="el-icon-arrow-left"></i>退回</el-button
          >
          <el-button
            type="danger"
            plain
            style="margin-top: 12px"
            @click="next"
            v-if="active == 0"
            :disabled="!sendCode"
            >下一步<i class="el-icon-arrow-right"></i
          ></el-button>
          <el-button
            type="danger"
            plain
            style="margin-top: 12px"
            @click="nextChangePass"
            v-if="active == 1"
            >下一步<i class="el-icon-arrow-right"></i
          ></el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="openBindEmail"
      :width="'800px'"
      :height="'400px'"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div slot="title" class="header-title">
        <span class="title-name">
          <i class="el-icon-message" style="margin-right: 10px"></i>
        </span>
        <span class="title-age">绑定邮箱</span>
      </div>
      <div class="changePass">
        <div class="changePassMiddle">
          <div class="changePassCode">
            <div
              style="
                position: absolute;
                width: 150%;
                top: -110px;
                left: -100px;
                color: rgb(243, 147, 106);
              "
            >
              <i class="el-icon-warning"></i
              >&nbsp;欢迎使用围群博客，为了方便用户账号管理，需要添加邮箱验证，邮箱仅用于账号管理，并无其他用途，请放心绑定！不绑定邮箱则无法使用本博客，感谢谅解
            </div>
            <el-input
              placeholder="请输入邮箱"
              v-model="bindEmail"
              maxlength="30"
              show-word-limit
              clearable
            ></el-input>
            <el-input
              v-model="emailCode"
              placeholder="验证码"
              style="width: 60%; top: 30px"
            ></el-input
            >&nbsp;
            <el-button
              type="primary"
              :disabled="disable"
              :class="{ codeGeting: isGeting }"
              style="position: absolute; width: 32%; top: 100px"
              @click="getEmailCode"
              >{{ getCode }}</el-button
            >
            <div
              style="
                position: absolute;
                width: 100%;
                top: 150px;
                color: rgb(230, 162, 60);
              "
              v-show="sendCode"
            >
              <i class="el-icon-warning"></i>&nbsp;验证码已发送，一分钟内有效，请注意查收!
            </div>
          </div>
          <el-button
            type="danger"
            style="margin-top: 100px; margin-left: 230px"
            @click="updateEmailbtn"
            :disabled="!isSendEmailCode"
            >确定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { $FindMyAccountMess } from "@/assets/api/user.js";
import { $bindEmailCode } from "@/assets/api/user.js";
import { $updateMyEmail } from "@/assets/api/user.js";
import { $updatePassCode } from "@/assets/api/user.js";
import { $codeIsCorrect } from "@/assets/api/user.js";
import { $changeAccountPass } from "@/assets/api/user.js";
import { $loginOut } from "@/assets/api/user.js";
import { findMyAccountType } from "@/assets/api/user.js";
export default {
  name: "index",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      editableTabsValue: "2",
      editableTabs: [
        {
          title: "Tab 1",
          name: "1",
          content: "Tab 1 content",
        },
        {
          title: "Tab 2",
          name: "2",
          content: "Tab 2 content",
        },
      ],
      tabIndex: 2,
      isSendEmailCode: false, //是否发送了验证码
      emailCode: "", //邮箱验证码
      openBindEmail: false, //绑定邮箱弹框
      bindEmail: "", //申请绑定的邮箱
      search: "", //搜索框内容
      activeIndex: "1", //单前激活的菜单
      sendCode: false, //验证是否已经发送
      codeSuccess: false, //验证码验证成功
      isChangePass: false,
      isCollapse: false,
      userMess: {
        //用户信息
        phone: "",
      },
      circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      changePass: false,
      active: 0,
      smsCode: {
        //密码修改短信验证
        phone: "",
        sms: "",
      },
      getCode: "获取验证码",
      isGeting: false, //60秒内重新获取验证码
      count: 60,
      disable: false,
      ruleForm: {
        //重新输入密码
        pass: "",
        checkPass: "",
      },
      rules: {
        //两次输入密码的规则
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
      },
      subTitle: "",
      breadList: [], // 路由集合
    };
  },
  created() {
    this.isLogin();
    this.getBreadcrumb();
  },
  watch: {
    $route(to, from) {
      this.getBreadcrumb();
    },
  },
  methods: {
    getBreadcrumb() {
      let matched = this.$route.matched;
      // console.log(matched);
      // 如果不是首页
      matched = [{ path: "/index", meta: { title: "首页" } }].concat(matched);
      this.breadList = matched;
      this.breadList.shift();
      this.breadList.shift();
      if (this.breadList[0].meta.title == "首页") {
        this.breadList.shift();
      } else {
        var url = this.breadList[0].meta.title;
        //  var bread0 = JSON.parse(JSON.stringify(this.breadList[0]));
        const strArr = url.split("/");
        for (var i = 0; i < strArr.length; i++) {
          var bread = {
            meta:{
              title:""
            }
          }
          var str = strArr[i];
           bread.meta.title = JSON.parse(JSON.stringify(str));
          this.breadList[i] = JSON.parse(JSON.stringify(bread));
        }
        
      }
    },
    updateEmailbtn() {
      $updateMyEmail(this.bindEmail, this.emailCode)
        .then((res) => {
          this.message(res);
          if (res.data.success) {
            this.openBindEmail = false;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    searchFun() {
      this.activeIndex = "2";
      sessionStorage.setItem("searchValue", this.search);

      if (this.$route.path != "/articleAdmin") {
        this.$router.push({
          name: "articleAdmin",
        });
      } else {
        location.reload();
      }
    },
    nextChangePass() {
      //进行密码修改
      if (this.ruleForm.pass == "" || this.ruleForm.pass !== this.ruleForm.checkPass) {
        this.$message({
          message: "检查密码输入",
          type: "error",
        });
        return;
      }
      $changeAccountPass(this.ruleForm.pass).then((res) => {
        if (res.data.success) {
          this.isChangePass = true;
          this.active = this.active + 2;
          var n = 5;
          var countDown = setInterval(() => {
            this.subTitle = "请重新登录, " + n + " 秒钟之后自动退出登录...";
            if (n < 0) {
              clearInterval(countDown);
              this.loginOut();
            }
            n--;
          }, 1000);
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
          });
          this.active++;
        }
      });
    },
    getVerifyCode() {
      //获取验证码
      this.$message({
        type: "success",
        message: "正在发送，请稍候",
      });
      this.disable = true;
      $updatePassCode()
        .then((res) => {
          this.$message({
            message: res.data.message,
            type: res.data.success ? "success" : "error",
          });
          if (res.data.success) {
            this.sendCode = true;

            var countDown = setInterval(() => {
              if (this.count < 1) {
                this.isGeting = false;
                this.disable = false;
                this.getCode = "获取验证码";
                this.count = 60;
                clearInterval(countDown);
              } else {
                this.isGeting = true;

                this.getCode = this.count-- + "s后重发";
              }
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getEmailCode() {
      //获取验证码
      this.$message({
        type: "success",
        message: "正在发送，请稍候",
      });
      this.disable = true;
      $bindEmailCode(this.bindEmail)
        .then((res) => {
          this.message(res);
          if (res.data.success) {
            this.isSendEmailCode = true;
            this.sendCode = true;
            var countDown = setInterval(() => {
              if (this.count < 1) {
                this.isGeting = false;
                this.disable = false;
                this.getCode = "获取验证码";
                this.count = 60;
                clearInterval(countDown);
              } else {
                this.isGeting = true;
                this.getCode = this.count-- + "s后重发";
              }
            }, 1000);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    next() {
      //跳转到修改修改密码阶段
      $codeIsCorrect(this.smsCode.sms).then((res) => {
        if (res.data.success) {
          this.active++;
        } else {
          this.$message({
            message: res.data.message,
            type: "error",
          });
        }
      });
    },
    changePassBtn() {
      this.changePass = true;
    },
    baseMess() {
      this.$router.push({
        name: "baseMess",
      });
    },
    isLogin() {
      findMyAccountType()
        .then((res) => {
          if (!res.data.success || res.data.data.findMyAccountType == 0) {
            this.$message({
              type: "error",
              message: "权限不足，请登录管理员账号",
            });
            this.loading = false;
            this.$router.push({
              name: "login",
            });
            return;
          } else {
            $FindMyAccountMess()
              .then((res) => {
                if (res.data.success) {
                  if (
                    res.data.data.findMyAccountMess.email == null ||
                    res.data.data.findMyAccountMess.email == "" ||
                    res.data.data.findMyAccountMess.email.length == 0
                  ) {
                    this.openBindEmail = true;
                  }
                  this.$myContent.setUserMess(
                    JSON.parse(JSON.stringify(res.data.data.findMyAccountMess))
                  ), //全局变量
                    sessionStorage.setItem(
                      "uid",
                      JSON.stringify(res.data.data.findMyAccountMess.id)
                    );
                  this.userMess = res.data.data.findMyAccountMess;
                  this.userChangeMess = res.data.data.findMyAccountMess;
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    opemMenu() {
      this.isCollapse = !this.isCollapse;
    },
    toIndex() {
      this.$router.push({
        name: "index",
      });
    },
    toArticle() {
      this.$router.push({
        name: "articleAdmin",
      });
    },
    toNodeList() {
      this.$router.push({
        name: "nodeList",
      });
    },
    toCodeAdmin() {
      this.$router.push({
        name: "codeAdmin",
      });
    },
    toProjectAdmin() {
      this.$router.push({
        name: "projectAdmin",
      });
    },
    toTagAdmin() {
      this.$router.push({
        name: "tagAdmin",
      });
    },
    toTagTypeAdmin() {
      this.$router.push({
        name: "tagTypeAdmin",
      });
    },
    toAboutAdmin() {
      this.$router.push({
        name: "aboutAdmin",
      });
    },
    toUserAdmin() {
      this.$router.push({
        name: "userAdmin",
      });
    },
    toRoleAdmin() {
      this.$router.push({
        name: "roleAdmin",
      });
    },
    toMenuAdmin() {
      this.$router.push({
        name: "menuAdmin",
      });
    },
    toCommunity() {
      this.$router.push({
        name: "community",
      });
    },

    //退出登录
    loginOut() {
      $loginOut().then((res) => {
        if (res.data.success) {
          sessionStorage.clear();
          this.$message({
            message: "已退出登录，感谢使用围群系统",
            type: "success",
          });
          this.$router.push({
            name: "login",
          });
        } else {
          this.$message({
            message: "退出登录失败，请重新尝试",
            type: "error",
          });
        }
      });
    },
  },
};
</script>

<style>
span {
  font-family: "Lucida Console", "Courier New", monospace;
}
</style>

<style scoped>
.breadcrumb-class {
  float: left;
  width: 300px;
  margin-top: 20px;
  display: inline-block;
}

.tabs {
  width: 500px;
  float: left;
}
.search-box {
  /* 绝对定位 水平垂直居中 */
  position: absolute;
  top: 40px;
  left: 1150px;
  width: 240px;

  transform: translate(-50%, -50%);
  background-color: #fff;
  height: 20px;
  padding: 10px;
  border-radius: 40px;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: #2f3640;
  font-size: 16px;
  line-height: 20px;
  width: 200px;
  padding: 0 6px;
  /* 动画过渡 */
  transition: 0.4s;
}

.search-btn {
  color: #e84118;
  float: right;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: rgb(0, 255, 255);
  /* 弹性布局 水平垂直居中 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  /* 动画过渡 */
  transition: 0.5s;
}

.search-box:hover .search-txt {
  width: 200px;
  padding: 0 6px;
}

.search-box:hover .search-btn {
  background-color: rgb(233, 60, 60);
}

.head-menu {
  min-width: 1300px;
}

.main {
  height: 90vh;
  overflow-y: scroll;
  min-width: 1300px;
}

.contianer {
  height: 96vh;
}

.changePassMiddle {
  width: 300px;
  height: 100px;
  position: absolute;
  bottom: 180px;
  left: 28%;
  padding: 30px;
}

.changePassBotton {
  position: absolute;
  bottom: 100px;
  right: 10%;
}

.changePass {
  height: 350px;
  padding: 50px;
  padding-top: 20px;
}

.userHeadimg {
  display: inline-block;
}

.userName {
  margin: 10px;
  position: relative;
  bottom: 13px;
  display: inline-block;
}

.el-dropdown-link {
  text-align: center;
  user-select: none;
}

.el-dropdown-link:i {
  top: 10px;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.userDropdown {
  position: relative;
  top: 0px;
  margin: 10px;
}
</style>
